package pe.com.pgn.consolidadorventas.servidorcentral.util;

import java.util.Hashtable;

import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NameNotFoundException;
import javax.naming.NamingException;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

import org.apache.log4j.Logger;

public class LdapSecurity {

	static Logger logger = Logger.getLogger(LdapSecurity.class);

	String ip;
	String username;
	String password;
	String baseDn;
	
	Hashtable<String, Object> env;
	LdapContext ctx;
	
	public LdapSecurity(){}
	
    public void inicializarContexto(){
    	env = new Hashtable<String, Object>();
		env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
		env.put(Context.PROVIDER_URL,"ldap://"+ip+"/"+baseDn);
		env.put(Context.SECURITY_AUTHENTICATION, "simple");
		try {
			ctx = new InitialLdapContext(env, null);
		} catch (NamingException e) {
			LoggerUtil.error(logger, e.getExplanation());
		}
    }
    
    public int autenticar(){
    	int rpta = 0;
    	try {
    		ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, "uid="+username+",ou=Users,"+baseDn);
    		ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
    		ctx.reconnect(null);
			rpta = Constantes.LDAP_AUTENTICACION_CORRECTA;
			ctx.close();
		}catch (AuthenticationException a){
			LoggerUtil.error(logger,a.getExplanation());
			//mensaje = "Usuario y clave no validos";
			rpta = Constantes.LDAP_DATOS_INCORRECTOS;
		}catch (NameNotFoundException n){
			LoggerUtil.error(logger,n.getExplanation());
			//mensaje = "No se encuentran datos del usuario "+username;
			rpta = Constantes.LDAP_NO_HAY_DATOS_USUARIO;
		}catch (NamingException e) {
			LoggerUtil.error(logger, e.getExplanation());
			//mensaje = e.getMessage();
			rpta = Constantes.LDAP_ERROR_CONEXION;
		}catch(Exception e){
			LoggerUtil.error(logger, e.getLocalizedMessage());
			//mensaje = e.getMessage();
			rpta = Constantes.LDAP_EXCEPCION_GENERAL;
		}
    	return rpta;
    }
    
	public String getIp() {
		return ip;
	}
	public void setIp(String ip) {
		this.ip = ip;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getBaseDn() {
		return baseDn;
	}
	public void setBaseDn(String baseDn) {
		this.baseDn = baseDn;
	}
	
	
}
